<template>
  <div class="user-detail-container">
    <!-- 用户基本信息卡片 -->
    <a-card class="user-info-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <UserOutlined /> 员工信息
          <a-button @click="goBack" size="small" style="margin-left: 16px">
            <template #icon><LeftOutlined /></template>
            返回
          </a-button>
        </div>
      </template>
      <a-descriptions
        :column="{ xs: 1, sm: 2, md: 4 }"
        class="user-descriptions"
        bordered
        size="small"
      >
        <a-descriptions-item label="员工姓名" class="description-item">{{
          userInfo.name
        }}</a-descriptions-item>
        <a-descriptions-item label="车牌号" class="description-item">
          {{ userInfo.plateNumber }}
          <a-tag v-if="userInfo.isNewEnergy" color="green">新能源</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="手机号" class="description-item">{{
          userInfo.phone
        }}</a-descriptions-item>
        <a-descriptions-item label="本季度取消次数" class="description-item">{{
          userInfo.cancelCount
        }}</a-descriptions-item>

        <a-descriptions-item label="当季度剩余额度" class="description-item">
          <span
            :class="
              getQuotaTextClass(
                userInfo.currentQuotaRemaining,
                userInfo.currentQuotaTotal
              )
            "
          >
            {{ userInfo.currentQuotaRemaining }}/{{
              userInfo.currentQuotaTotal
            }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="下季度剩余额度" class="description-item">
          <span
            :class="
              getQuotaTextClass(
                userInfo.nextQuotaRemaining,
                userInfo.nextQuotaTotal
              )
            "
          >
            {{ userInfo.nextQuotaRemaining }}/{{ userInfo.nextQuotaTotal }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item
          label="预约权限状态"
          class="description-item"
          :span="2"
        >
          <div class="quota-control">
            <a-switch
              :checked="!userInfo.isDisabled"
              @change="handleDisableToggle"
              checked-children="正常"
              un-checked-children="禁用"
            />
            <span
              class="quota-status"
              :class="{ disabled: userInfo.isDisabled }"
            >
              {{
                userInfo.isDisabled ? "下季度不发放额度" : "下季度正常发放额度"
              }}
            </span>
          </div>
        </a-descriptions-item>
        <a-descriptions-item
          label="增加预约额度"
          class="description-item"
          :span="2"
        >
          <div class="quota-add-form">
            <a-input-number
              v-model:value="extraQuotaInput"
              :min="0.5"
              :max="10"
              :step="0.5"
              style="width: 100px"
            />
            <a-button
              type="primary"
              size="small"
              @click="saveExtraQuota"
              :loading="quotaLoading"
              style="margin-left: 8px"
            >
              确认增加
            </a-button>
            <span class="quota-note"
              >注：增加的额度将立即生效，每次最少增加0.5额度</span
            >
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <!-- 预约记录筛选器 -->
    <div class="reservation-filter">
      <div class="filter-title">
        <h3>预约记录</h3>
      </div>
      <div class="filter-actions">
        <a-range-picker
          v-model:value="dateRange"
          format="YYYY-MM-DD"
          :placeholder="['开始日期', '结束日期']"
          @change="handleDateRangeChange"
        />
        <a-button type="primary" @click="exportData">
          <template #icon><DownloadOutlined /></template>
          导出记录
        </a-button>
      </div>
    </div>

    <!-- 预约记录表格 -->
    <a-table
      :columns="columns"
      :data-source="filteredReservations"
      :pagination="false"
      :loading="loading"
      row-key="id"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <!-- 预约状态 -->
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
      </template>
    </a-table>

    <!-- 无数据提示 -->
    <div class="no-data" v-if="filteredReservations.length === 0 && !loading">
      <a-empty description="暂无预约记录" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  UserOutlined,
  DownloadOutlined,
  LeftOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import dayjs from "dayjs";
import { getUserDetail, updateUser } from "../api/index"; // 导入updateUser API

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const userId = route.params.id;

// 添加返回函数
const goBack = () => {
  router.push("/");
};

// 用户基本信息
const userInfo = reactive({
  id: userId,
  name: "加载中...",
  plateNumber: "",
  isNewEnergy: false,
  phone: "",
  currentQuotaRemaining: 0,
  currentQuotaTotal: 30,
  nextQuotaRemaining: 0,
  nextQuotaTotal: 30,
  cancelCount: 0,
  isDisabled: false,
});

// 日期范围
const dateRange = ref([]);

// 预约记录
const reservations = ref([]);

// 简化的额度相关数据
const extraQuota = ref(0); // 当前额外额度
const extraQuotaInput = ref(0); // 新的额外额度输入值
const quotaLoading = ref(false);

// 表格列定义
const columns = [
  {
    title: "预约日期",
    dataIndex: "date",
    key: "date",
    sorter: (a, b) => new Date(a.date) - new Date(b.date),
  },
  //   {
  //     title: '时段',
  //     dataIndex: 'timeSlot',
  //     key: 'timeSlot'
  //   },
  {
    title: "车位号",
    dataIndex: "parkingSpace",
    key: "parkingSpace",
  },
  {
    title: "预约时间",
    dataIndex: "reservationTime",
    key: "reservationTime",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    filters: [
      { text: "已完成", value: "completed" },
      { text: "已取消", value: "canceled" },
      { text: "进行中", value: "active" },
    ],
    onFilter: (value, record) => record.status === value,
  },
];

// 根据日期筛选预约记录
const filteredReservations = computed(() => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    return reservations.value;
  }

  const startDate = dateRange.value[0].startOf("day");
  const endDate = dateRange.value[1].endOf("day");

  return reservations.value.filter((record) => {
    const recordDate = dayjs(record.date);
    return recordDate.isAfter(startDate) && recordDate.isBefore(endDate);
  });
});

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    dateRange.value = dates;
  } else {
    dateRange.value = [];
  }
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case "completed":
      return "green";
    case "canceled":
      return "red";
    case "active":
      return "blue";
    default:
      return "default";
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case "completed":
      return "已完成";
    case "canceled":
      return "已取消";
    case "active":
      return "进行中";
    default:
      return "未知";
  }
};

// 获取配额文本样式
const getQuotaTextClass = (remaining, total) => {
  const ratio = remaining / total;
  if (ratio <= 0.2) return "quota-danger";
  if (ratio <= 0.5) return "quota-warning";
  return "quota-normal";
};

// 处理禁用开关切换
const handleDisableToggle = (value) => {
  // value为true表示启用，false表示禁用
  // 显示加载状态
  const loadingMessage = message.loading("正在更新状态...", 0);

  // 调用API更新用户状态
  updateUser(userId, {
    is_active: value, // true表示启用，false表示禁用
  })
    .then((response) => {
      // 关闭加载提示
      loadingMessage();

      if (response && response.code === 200) {
        // 更新本地状态
        userInfo.isDisabled = !value;

        // 显示成功消息
        if (!value) {
          message.success("已禁用用户预约权限，下季度将不发放预约额度");
        } else {
          message.success("已启用用户预约权限，下季度将正常发放预约额度");
        }
      } else {
        message.error("更新状态失败：" + (response.message || "未知错误"));
      }
    })
    .catch((error) => {
      // 关闭加载提示
      loadingMessage();

      console.error("更新用户状态出错:", error);
      message.error("更新用户状态失败，请检查网络连接");
    });
};

// 导出数据
const exportData = () => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();

  // 格式化导出数据
  const exportRecords = filteredReservations.value.map((record) => {
    return {
      预约日期: record.date,
      时段: record.timeSlot,
      车位号: record.parkingSpace,
      预约时间: record.reservationTime,
      状态: getStatusText(record.status),
    };
  });

  // 将数据转换为工作表
  const worksheet = XLSX.utils.json_to_sheet(exportRecords);

  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 预约日期列宽
    { wch: 15 }, // 时段列宽
    { wch: 10 }, // 车位号列宽
    { wch: 20 }, // 预约时间列宽
    { wch: 10 }, // 状态列宽
  ];

  worksheet["!cols"] = colWidths;

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "预约记录");

  // 生成xlsx文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });

  saveAs(
    blob,
    `${userInfo.name}_预约记录_${new Date().toISOString().slice(0, 10)}.xlsx`
  );

  message.success("预约记录导出成功");
};

// 获取用户详情数据
const fetchUserData = () => {
  loading.value = true;

  // 调用API获取用户详情
  getUserDetail(userId)
    .then((response) => {
      if (response && response.code === 200 && response.data) {
        // 从API返回的数据中提取需要的信息
        const userData = response.data;

        // 更新用户信息
        Object.assign(userInfo, {
          id: userData.id,
          name: userData.name || "",
          plateNumber: userData.license_plate || "",
          isNewEnergy: userData.is_new_energy || false,
          phone: userData.phone || "",
          currentQuotaRemaining: userData.current_quarter_quota_remaining || 0,
          currentQuotaTotal: userData.current_quarter_quota || 30,
          nextQuotaRemaining: userData.next_quarter_quota_remaining || 0,
          nextQuotaTotal: userData.next_quarter_quota || 30,
          cancelCount: userData.cancel_quota || 0,
          isDisabled: !userData.is_active, // 注意这里取反了，API中is_active=true表示启用
        });

        // 获取预约记录（如果API返回了预约记录数据）
        if (userData.reservations && Array.isArray(userData.reservations)) {
          reservations.value = userData.reservations.map((reservation) => ({
            id: reservation.id,
            date: reservation.date,
            timeSlot: reservation.time_slot || "全天",
            parkingSpace: reservation.parking_space || "",
            reservationTime: reservation.created_at || "",
            status: reservation.status || "completed",
          }));
        }

        message.success("用户详情加载成功");
      } else {
        message.error("获取用户详情失败：" + (response.message || "未知错误"));
      }
    })
    .catch((error) => {
      console.error("获取用户详情出错:", error);
      message.error("获取用户详情失败，请检查网络连接");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 保存额外额度 - 修改为增加模式
const saveExtraQuota = () => {
  // 检查输入是否有效
  if (extraQuotaInput.value < 0.5) {
    message.error("增加的额度不能小于0.5");
    return;
  }

  quotaLoading.value = true;
  updateUser(userId, {
    current_quarter_quota_add: extraQuotaInput.value,
  })
    .then((response) => {
      message.success(
        `成功增加 ${extraQuotaInput.value} 额度，当前剩余额度：${
          userInfo.currentQuotaRemaining + extraQuotaInput.value
        }`
      );
      extraQuotaInput.value = 0.5;

      quotaLoading.value = false;
      fetchUserData();
    })
    .catch((error) => {
      console.error("增加额度失败:", error);
      message.error("增加额度失败，请检查网络连接");
    })
    .finally(() => {
      quotaLoading.value = false;
    });
};

// 初始化额外额度显示
onMounted(() => {
  fetchUserData();
  // 设置初始增加额度为0.5
  extraQuotaInput.value = 0.5;
});
</script>

<style scoped>
.user-detail-container {
  padding: 24px 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.user-info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
}

/* 调整描述列表样式 */
.user-descriptions {
  width: 100%;
  table-layout: fixed; /* 强制表格使用固定布局 */
}

/* 修正描述列表内部表格样式，使用固定布局 */
:deep(.ant-descriptions-view) {
  width: 100%;
  table-layout: fixed;
}

/* 减小内边距使其更紧凑 */
:deep(.description-item .ant-descriptions-item-content) {
  padding: 8px 12px;
  width: auto; /* 移除固定宽度，使用表格固定布局控制 */
  box-sizing: border-box;
}

:deep(.ant-descriptions-bordered .ant-descriptions-item-label) {
  padding: 8px 12px;
  font-weight: 500;
  width: auto; /* 移除固定宽度，使用表格固定布局控制 */
  text-align: right;
  box-sizing: border-box;
}

/* 移除之前的固定宽度设置，改用表格布局控制 */
:deep(.ant-descriptions-item-content) {
  box-sizing: border-box;
}

/* 优化开关组件样式 */
.quota-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quota-status {
  font-size: 13px;
}

.quota-status.disabled {
  color: #ff4d4f;
}

.reservation-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.filter-title h3 {
  margin: 0;
  font-size: 18px;
}

.filter-actions {
  display: flex;
  gap: 16px;
}

.no-data {
  margin-top: 48px;
}

/* 额度文本样式 */
.quota-normal {
  color: #52c41a;
  font-weight: 500;
}

.quota-warning {
  color: #faad14;
  font-weight: 500;
}

.quota-danger {
  color: #f5222d;
  font-weight: 500;
}

.detail-card {
  margin-bottom: 24px;
}

.simple-quota-form {
  display: flex;
  flex-direction: column;
}

.quota-input-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.quota-label {
  font-weight: 500;
  margin-right: 8px;
}

.quota-note {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-left: 8px;
}

.quota-add-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>